<template>
  <div class="article-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <el-button 
            v-if="articlePublishEnabled" 
            type="primary" 
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增文章
          </el-button>
          <el-tag 
            v-else 
            type="danger" 
            size="small"
            style="margin-left: 10px;"
          >
            文章发布功能已禁用
          </el-tag>
        </div>
      </template>
      
      <!-- 文章列表 -->
      <el-table :data="articleList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="summary" label="摘要" min-width="150" show-overflow-tooltip />
        <el-table-column prop="authorName" label="作者" width="100" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column label="标签" width="150">
          <template #default="scope">
            <el-tag 
              v-for="tag in scope.row.tags || []" 
              :key="tag.id" 
              size="small" 
              style="margin-right: 5px; margin-bottom: 2px"
            >
              {{ tag.name }}
            </el-tag>
            <span v-if="!scope.row.tags || scope.row.tags.length === 0" class="text-gray-400">无标签</span>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="80" />
        <el-table-column prop="likeCount" label="点赞数" width="80" />
        <el-table-column prop="isPublished" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPublished === 1 ? 'success' : 'warning'">
              {{ scope.row.isPublished === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                v-if="articlePublishEnabled"
                size="small" 
                :type="scope.row.isPublished === 1 ? 'warning' : 'success'"
                @click="handleTogglePublish(scope.row)"
              >
                {{ scope.row.isPublished === 1 ? '下架' : '发布' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 文章编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
      @close="cancelEdit"
    >
      <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="articleFormRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input 
            v-model="articleForm.summary" 
            type="textarea" 
            :rows="3"
            placeholder="请输入文章摘要" 
          />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="articleForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tagIds">
          <el-select 
            v-model="articleForm.tagIds" 
            placeholder="请选择标签" 
            multiple 
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="tag in tagList"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="articleForm.content" 
            type="textarea" 
            :rows="15"
            placeholder="请输入文章内容" 
          />
        </el-form-item>
        <el-form-item label="发布状态">
          <el-switch
            v-if="articlePublishEnabled"
            v-model="articleForm.isPublished"
            active-text="发布"
            inactive-text="草稿"
            :active-value="1"
            :inactive-value="0"
          />
          <el-tag 
            v-else 
            type="danger" 
            size="small"
          >
            文章发布功能已禁用
          </el-tag>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getArticleList, 
  createArticle, 
  updateArticle, 
  deleteArticle, 
  togglePublishStatus 
} from '@/api/article'
import { getAllCategories } from '@/api/category'
import { getAllTags } from '@/api/tag'
import { getConfigStatus } from '@/api/system'
import { on, off, EVENT_TYPES } from '@/utils/eventBus'

const userStore = useUserStore()

// 表格数据
const articleList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分类数据
const categoryList = ref([])

// 标签数据
const tagList = ref([])

// 配置状态
const articlePublishEnabled = ref(true)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const articleForm = reactive({
  id: null,
  title: '',
  summary: '',
  content: '',
  categoryId: null,
  tagIds: [],
  isPublished: 0
})
const articleFormRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { max: 255, message: '标题长度不能超过255个字符', trigger: 'blur' }
  ],
  summary: [
    { max: 255, message: '摘要长度不能超过255个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}
const articleFormRef = ref()

// 获取文章列表
const fetchArticleList = async () => {
  loading.value = true
  try {
    const response = await getArticleList({
      current: currentPage.value,
      size: pageSize.value
    })
    
    if (response.code === 200) {
      articleList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取文章列表失败')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 新增文章
const handleAdd = async () => {
  isEdit.value = false
  dialogTitle.value = '新增文章'
  resetForm()
  // 重新获取最新的分类和标签数据
  await Promise.all([fetchCategoryList(), fetchTagList()])
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = async (article) => {
  isEdit.value = true
  dialogTitle.value = '编辑文章'
  
  // 获取文章详情（包含标签）
  try {
    const response = await getArticleDetail(article.id)
    if (response.code === 200) {
      const articleData = response.data
      Object.assign(articleForm, {
        id: articleData.id,
        title: articleData.title,
        summary: articleData.summary,
        content: articleData.content,
        categoryId: articleData.categoryId,
        isPublished: articleData.isPublished,
        tagIds: articleData.tags ? articleData.tags.map(tag => tag.id) : []
      })
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    // 如果获取详情失败，使用列表中的数据
    Object.assign(articleForm, {
      id: article.id,
      title: article.title,
      summary: article.summary,
      content: article.content,
      categoryId: article.categoryId,
      isPublished: article.isPublished,
      tagIds: []
    })
  }
  
  // 重新获取最新的分类和标签数据
  await Promise.all([fetchCategoryList(), fetchTagList()])
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await articleFormRef.value.validate()
    
    // 设置作者ID
    articleForm.authorId = userStore.userInfo.id
    
    let response
    if (isEdit.value) {
      response = await updateArticle(articleForm.id, articleForm)
    } else {
      response = await createArticle(articleForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      await fetchArticleList()
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 取消编辑
const cancelEdit = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(articleForm, {
    id: null,
    title: '',
    summary: '',
    content: '',
    categoryId: null,
    tagIds: [],
    isPublished: 0
  })
  articleFormRef.value?.resetFields()
}

// 切换发布状态
const handleTogglePublish = async (article) => {
  try {
    const isPublished = article.isPublished === 0 ? true : false
    const response = await togglePublishStatus(article.id, isPublished)
    
    if (response.code === 200) {
      ElMessage.success(isPublished ? '发布成功' : '取消发布成功')
      await fetchArticleList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('切换发布状态失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除文章
const handleDelete = async (article) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章"${article.title}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteArticle(article.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await fetchArticleList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticleList()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await getAllCategories()
    if (response.code === 200) {
      categoryList.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取标签列表
const fetchTagList = async () => {
  try {
    const response = await getAllTags()
    if (response.code === 200) {
      tagList.value = response.data || []
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 检查配置状态
const checkConfigStatus = async () => {
  try {
    const response = await getConfigStatus()
    if (response.code === 200) {
      articlePublishEnabled.value = response.data.articlePublishEnabled
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
    ElMessage.error('获取配置状态失败')
  }
}

onMounted(() => {
  fetchArticleList()
  fetchCategoryList()
  fetchTagList()
  checkConfigStatus()
  
  // 监听分类数据更新事件
  on(EVENT_TYPES.CATEGORY_CREATED, handleCategoryDataChange)
  on(EVENT_TYPES.CATEGORY_UPDATED, handleCategoryDataChange)
  on(EVENT_TYPES.CATEGORY_DELETED, handleCategoryDataChange)
  on(EVENT_TYPES.REFRESH_CATEGORIES, fetchCategoryList)
  
  // 监听标签数据更新事件
  on(EVENT_TYPES.TAG_CREATED, handleTagDataChange)
  on(EVENT_TYPES.TAG_UPDATED, handleTagDataChange)
  on(EVENT_TYPES.TAG_DELETED, handleTagDataChange)
  on(EVENT_TYPES.REFRESH_TAGS, fetchTagList)
})

// 当组件激活时（从其他页面返回时）重新获取数据
onActivated(() => {
  fetchCategoryList()
  fetchTagList()
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  off(EVENT_TYPES.CATEGORY_CREATED, handleCategoryDataChange)
  off(EVENT_TYPES.CATEGORY_UPDATED, handleCategoryDataChange)
  off(EVENT_TYPES.CATEGORY_DELETED, handleCategoryDataChange)
  off(EVENT_TYPES.REFRESH_CATEGORIES, fetchCategoryList)
  
  off(EVENT_TYPES.TAG_CREATED, handleTagDataChange)
  off(EVENT_TYPES.TAG_UPDATED, handleTagDataChange)
  off(EVENT_TYPES.TAG_DELETED, handleTagDataChange)
  off(EVENT_TYPES.REFRESH_TAGS, fetchTagList)
})

// 处理分类数据变化
const handleCategoryDataChange = () => {
  console.log('检测到分类数据变化，刷新分类列表')
  fetchCategoryList()
}

// 处理标签数据变化
const handleTagDataChange = () => {
  console.log('检测到标签数据变化，刷新标签列表')
  fetchTagList()
}
</script>

<style lang="scss" scoped>
.article-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  
  .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 12px;
    min-width: auto;
  }
}
</style>
